from goods.models import GoodsChannel


def get_categories():
    # 定义好空字典
    categories = {}
    # 查询所有得频道
    channels = GoodsChannel.objects.order_by("id").all()
    # 拼接好前端需要得数据得格式
    for channel in channels:
        group_id = channel.group_id
        if group_id not in categories:
            categories[group_id] = {
                'channels': [],
                'sub_cats': []
            }
            # 添加频道信息
        cat1 = channel.category  # 一级分类GoodsCategory
        cat1_dict = {
            'url': channel.url,
            'name': cat1.name
        }
        categories[group_id]['channels'].append(cat1_dict)
        # 添加二级分类，三级分类
        cats2 = cat1.subs.all()
        for cat2 in cats2:
            categories[group_id]['sub_cats'].append({
                'name': cat2.name,
                'subs': cat2.subs.all()
            })

    return categories
